package com.tdtxdcxm.ruralcommunity.slice;


import com.tdtxdcxm.ruralcommunity.ResourceTable;
import com.tdtxdcxm.ruralcommunity.appruntime.DataCenterControl;
import com.tdtxdcxm.ruralcommunity.appruntime.UserConfigInfo;
import com.tdtxdcxm.ruralcommunity.httpmanagers.ThreadPoolUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import ohos.net.NetStatusCallback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class RegisterSlice extends AbilitySlice implements Component.ClickedListener{

    private Boolean toanotherslice = false;
    private String[][] userinfo = new String[5][2];
    private TextField reg_usernametfd,reg_passwordtfd,reg_email,reg_xb,reg_nl;
    private RadioContainer reg_dll2_1_radiocontainer;
    private RadioButton reg_dll2_1_radiobut1,reg_dll2_1_radiobut2;
    private Button submitregister,reg_rbackbt;
    private Text reg_tstext;

    /*<****************http构造表单上传注册数据区域*****************/
    public void UpDataRegeisterInfo(String[][] userinfo){
        NetManager main_toplistnetmanger = NetManager.getInstance(this.getContext());
        if (!main_toplistnetmanger.hasDefaultNet()) {
            return;
        }
        ThreadPoolUtil.submit(() -> {
            NetHandle thenetHandle = main_toplistnetmanger.getDefaultNet();
            NetStatusCallback netStatusCallback = new NetStatusCallback() {};
            HttpURLConnection httpURLConnection = null;

            String urlString = DataCenterControl.serverIpWithPort + "register/?";
            try {
                URL url = new URL(urlString);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                URLConnection urlConnection = thenetHandle.openConnection(url, java.net.Proxy.NO_PROXY);
                if (urlConnection instanceof HttpURLConnection) {
                    httpURLConnection = (HttpURLConnection) urlConnection;

                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);

                    StringBuilder stringBuilder = new StringBuilder();

                    for(int i = 0;i < userinfo.length;i++){
                        if(i == 0){
                            stringBuilder.append(userinfo[0][0]);
                            stringBuilder.append("=");
                            stringBuilder.append(userinfo[0][1]);
                            continue;
                        }
                        stringBuilder.append("&");
                        stringBuilder.append(userinfo[i][0]);
                        stringBuilder.append("=");
                        stringBuilder.append(userinfo[i][1]);
                    }

                    byte[] b = stringBuilder.toString().getBytes();
                    httpURLConnection.getOutputStream().write(b);

                    try {
                        httpURLConnection.connect();
                    } catch (IOException e) {}
                    outputStream.flush();

                    try {
                        InputStream inputStream = urlConnection.getInputStream();
                        byte[] cache = new byte[2 * 1024];
                        int len = inputStream.read(cache);
                        while (len != -1) {
                            outputStream.write(cache, 0, len);
                            len = inputStream.read(cache);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = "";
                    result = new String(outputStream.toByteArray());
                    if(result.equals("OK")){
                        DataCenterControl.userName = userinfo[0][1];
                        DataCenterControl.gender = userinfo[3][1];
                        DataCenterControl.age = userinfo[4][1];
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                reg_tstext.setText("注册成功");
                                reg_usernametfd.setText("");
                                reg_passwordtfd.setText("");
                                reg_email.setText("");
                                reg_dll2_1_radiocontainer.cancelMarks();
                                reg_nl.setText("");

                                UserConfigInfo.pushData(RegisterSlice.this.getContext(),userinfo);//将注册数据写入本地数据库
                                toanotherslice = true;
                            }
                        });
                        present(new MainAbilitySlice(),new Intent());
                    }
                    else{
                        getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                reg_tstext.setText("注册失败");
                            }
                        });
                    }
                }
            } catch (IOException e) {

            } finally {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            }
        });
    }
    /******************http构造表单上传注册数据区域***************>*/

    private void initRegComponent() {
        reg_usernametfd = (TextField) findComponentById(ResourceTable.Id_reg_usernametfd);
        reg_passwordtfd = (TextField) findComponentById(ResourceTable.Id_reg_passwordtfd);
        reg_email = (TextField) findComponentById(ResourceTable.Id_reg_email);

        reg_dll2_1_radiocontainer = (RadioContainer) findComponentById(ResourceTable.Id_reg_dll2_1_radiocontainer);
        reg_dll2_1_radiobut1 = (RadioButton) findComponentById(ResourceTable.Id_reg_dll2_1_radiobut1);
        reg_dll2_1_radiobut2 = (RadioButton) findComponentById(ResourceTable.Id_reg_dll2_1_radiobut2);

        reg_nl = (TextField) findComponentById(ResourceTable.Id_reg_nl);
        reg_tstext = (Text) findComponentById(ResourceTable.Id_reg_tstext);
        submitregister = (Button) findComponentById(ResourceTable.Id_submitregister);
        reg_rbackbt = (Button) findComponentById(ResourceTable.Id_reg_rbackbt);


        reg_passwordtfd.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if(!s.equals("") && !s.matches("^[0-9]+$")){
                    reg_tstext.setText("只能是数字");
                    reg_passwordtfd.setText(s.substring(0,s.length() - 1));
                }
            }
        });
        reg_nl.addTextObserver(new Text.TextObserver() {
            @Override
            public void onTextUpdated(String s, int i, int i1, int i2) {
                if(!s.equals("") && !s.matches("^[0-9]+$")){
                    reg_tstext.setText("只能是数字");
                    reg_nl.setText(s.substring(0,s.length() - 1));
                }
            }
        });

        reg_dll2_1_radiocontainer.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                switch (radioContainer.getMarkedButtonId()){
                    case 0:
                        reg_tstext.setText(reg_dll2_1_radiobut1.getText());break;
                    case 1:
                        reg_tstext.setText(reg_dll2_1_radiobut2.getText());break;
                }
                reg_tstext.setText(radioContainer.getMarkedButtonId());
            }
        });
        submitregister.setClickedListener(this);
        reg_rbackbt.setClickedListener(this);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_registerpage);

        initRegComponent();
    }


    @Override
    public void onActive() {
        super.onActive();
        reg_tstext.setText("您好！");
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        if(toanotherslice){
            terminate();
        }

    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }



    @Override
    public void onClick(Component component) {
        if(component == submitregister){
            reg_tstext.setText("正在注册中......");
            reg_usernametfd.clearFocus();
            reg_email.clearFocus();
            reg_passwordtfd.clearFocus();
            reg_nl.clearFocus();
            reg_dll2_1_radiocontainer.clearFocus();
            if(reg_usernametfd.getText().equals(""))
            {

                reg_tstext.setText("账号不能为空！");
                return;
            }
            if(reg_passwordtfd.getText().equals(""))
            {

                reg_tstext.setText("密码不能为空！");
                return;
            }
            if(reg_passwordtfd.getText().length() > 8){

                reg_tstext.setText("密码不能超过8位！");
                return;
            }
            if(reg_email.getText().equals(""))
            {
                reg_tstext.setText("邮箱不能为空！");
                return;
            }
            if(reg_dll2_1_radiocontainer.getMarkedButtonId() != 0 && reg_dll2_1_radiocontainer.getMarkedButtonId() != 1)
            {

                reg_tstext.setText("性别未选择！");
                return;
            }
            if(reg_nl.getText().equals("") || Integer.parseInt(reg_nl.getText()) < 0 || Integer.parseInt(reg_nl.getText()) >200)
            {
                reg_tstext.setText("年龄不正确！（0-200岁）");
                return;
            }



            userinfo[0][0] = "username";
            userinfo[0][1] = reg_usernametfd.getText();

            userinfo[1][0] = "password";
            userinfo[1][1] = reg_passwordtfd.getText();

            userinfo[2][0] = "email";
            userinfo[2][1] = reg_email.getText();

            userinfo[3][0] = "gender";
            switch (reg_dll2_1_radiocontainer.getMarkedButtonId()){
                case 0:
                    userinfo[3][1] = reg_dll2_1_radiobut1.getText();break;
                case 1:
                    userinfo[3][1] = reg_dll2_1_radiobut2.getText();break;
            }

            userinfo[4][0] = "age";
            userinfo[4][1] = reg_nl.getText();

            UpDataRegeisterInfo(userinfo);

            toanotherslice = true;
        }
        if(component == reg_rbackbt)
        {
            reg_usernametfd.setText("");
            reg_passwordtfd.setText("");
            reg_email.setText("");
            reg_dll2_1_radiocontainer.cancelMarks();
            reg_nl.setText("");
            present(new StartPage(),new Intent());
            toanotherslice = true;
        }
    }
}
